export default {
  namespaced: true,
  state: {
    // 购物车的数组，用来存储购物车中每个商品的信息对象
    // 每个商品的信息对象，都包含如下 6 个属性：
    // { goods_id, goods_name, goods_price, goods_count, goods_small_logo, goods_state }
    cart: JSON.parse(uni.getStorageSync('cart') || '[]'),
  },
  mutations: {
    addToCart(state, goods) {
      const findResult = state.cart.find(g =>
        //当前查找的cart的id等于外面传的id
        g.goods_id === goods.goods_id)
      if (!findResult) {
        state.cart.push(goods)
      } else {
        findResult.goods_count++
      }
      this.commit('my_cart/saveToStorage')
    },
    //持久化购物车里面的信息
    saveToStorage(state) {
      uni.setStorageSync('cart', JSON.stringify(state.cart))
    },
    //更新购物车中商品的勾选状态
    updateGoodsState(state, goods) {
      const findResult = state.cart.find(g => g.goods_id === goods.goods_id)
      if (findResult) {
        findResult.goods_state = goods.goods_state
        this.commit('my_cart/saveToStorage')
      }
    },
    //更新购物车商品数量变化
    updateGoodsCount(state, goods) {
      const findResult = state.cart.find(g => g.goods_id === goods.goods_id)
      if (findResult) {
        findResult.goods_count = goods.goods_count
        this.commit('my_cart/saveToStorage')
      }
    },
    //滑动删除商品
    delGoods(state, goods_id) {
      state.cart = state.cart.filter(g => g.goods_id !== goods_id)
      this.commit('my_cart/saveToStorage')
    },
    //更新所有商品的勾选状态
    updateAllGoodsState(state, newState) {
      state.cart.forEach(g => g.goods_state = newState)
      this.commit('my_cart/saveToStorage')
    }
  },
  getters: {
    //商品的总数量
    total(state) {
      // let c = 0
      // state.cart.forEach(g => c += g.goods_count)
      // return c
      //改造
      return state.cart.reduce((total, item) =>
        total += item.goods_count, 0)
    },
    //动态计算勾选商品的总数量
    checkedCount(state) {
      return state.cart.filter(g => g.goods_state).reduce((total, item) =>
        total += item.goods_count, 0)
    },
    //动态计算勾选商品的总价格
    checkedPrice(state) {
      return state.cart.filter(g => g.goods_state).reduce((total, item) =>
        total += (item.goods_price * item.goods_count), 0).toFixed(2)
    },
    //动态计算勾选商品的状态
    checkedState(state) {
      return state.cart.every(g => g.goods_state)
    }
  }
}